package cn.livingCloud.controller.core.validator;

import cn.livingCloud.dto.EmployeeAccountFormDto;
import cn.livingCloud.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Created by 唐旭 on 2016/6/1.
 */
@Component
public class EmployeeAccountFormDtoValidator implements Validator {

    @Qualifier("userAccountServiceImpl")
    @Autowired
    private UserAccountService userAccountService;

    @Override
    public boolean supports(Class<?> aClass) {
        return EmployeeAccountFormDto.class.equals(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "employeeUuid", null, "请选择员工");
        EmployeeAccountFormDto formDto = (EmployeeAccountFormDto) target;
        String username = formDto.getUsername().trim();
        if (StringUtils.isEmpty(username)) {
            errors.rejectValue("username", null, "账号不能为空");
        }
        if (StringUtils.isEmpty(formDto.getUuid())) {
            if (userAccountService.check(username)) {
                errors.rejectValue("username", null, "账号重复");
            }
        }
        if (StringUtils.isEmpty(formDto.getUuid())) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", null, "请输入密码");
        }
    }
}
